package com.asia.algorithmcode.backTracking;

import java.util.ArrayList;
import java.util.List;

/**
 * @DESCRIPTION:
 * @USER: wanfu
 * @DATE: 2025/3/7 星期五 17:17
 */
public class SpiralOrder {


    public static List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> ans = new ArrayList<>();
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return ans;
        }

        int m = matrix.length;
        int n = matrix[0].length;

        int top = 0;
        int left = 0;
        int right = n - 1;
        int bottom = m - 1;

        while (left <= right && top <= bottom) {

            for (int i = left; i <= right; i++) {
                ans.add(matrix[top][i]);
            }

            for (int i = top + 1; i <= bottom; i++) {
                ans.add(matrix[i][right]);
            }
            if (left < right && top < bottom) {

                for (int i = right - 1; i >= left; i--) {
                    ans.add(matrix[bottom][i]);
                }

                for (int i = bottom - 1; i > top; i--) {
                    ans.add(matrix[i][left]);
                }
            }


            left++;
            top++;
            right--;
            bottom--;
        }

        return ans;
    }

    public static void main(String[] args) {

        int[][] arr = new int[][]{
                {1, 2, 3, 4},
                {5, 6, 7, 8},
                {9, 10, 11, 12}
        };

        System.out.println(spiralOrder(arr));

    }

}
